'use strict'

const Controller = require('egg').Controller

class MainController extends Controller {
  async index () {
    this.ctx.body = 'hi heyang'
  }

  async login() {
  
    let username = this.ctx.request.body.username
    let password = this.ctx.request.body.password
    
    const sql = " SELECT username FROM admin_user WHERE username = '"+username +
                  "' AND password = '"+password+"'"

    const res = await this.app.mysql.query(sql)

    if (res.length > 0) {
      let openId = new Date().getTime()
      this.ctx.session.openId = {"openId": openId}
      this.ctx.body = {
        'data': '登录成功',
        'openId': openId
      }
    } else {
      this.ctx.body = {
        'data': '登录失败'
      }
    }
  }

  async getTypeInfo () {
    let typeInfo = await this.app.mysql.select('type')
    this.ctx.body = {
      data: typeInfo
    }
  }

  async addArticle () {
    let tmpArticle = this.ctx.request.body
    const addInfo = await this.app.mysql.insert('article', tmpArticle)
    const insertSuccess = addInfo.affectedRows === 1
    const insertId = addInfo.insertId
    // console.log(addInfo)

    this.ctx.body = {
      success: insertSuccess,
      insertId: insertId
    }
  }

  async updateArticle () {
    let tmpArticle = this.ctx.request.body
    const result = await this.app.mysql.update('article', tmpArticle)
    const updateSuccess = result.affectedRows === 1
    this.ctx.body = {
      success: updateSuccess
    }
  } 

  async getArticleList () {
    let sql = 'SELECT article.id as id,' + 
              'article.title as title,' + 
              'article.introduce as introduce,' + 
              "FROM_UNIXTIME(article.addTime,'%Y-%m-%d %H:%m:%s') as addTime," + 
              'article.view_count as view_count,' + 
              'type.typeName as typeName ' + 
              'FROM article LEFT JOIN type ON article.type_id = type.Id ' +
              'ORDER BY article.id DESC '
    const result = await this.app.mysql.query(sql)
    this.ctx.body = {
      data: result
    }
  }

  async delArticle () {
    let id = this.ctx.params.id
    const result = await this.app.mysql.delete('article', {'id': id})
    this.ctx.body = {
      data: result
    }
  }

  async getArticleById () {
    let id = this.ctx.params.id
    let sql = 'SELECT article.id as id,' +
              'article.title as title,' +
              'article.introduce as introduce,' +
              "FROM_UNIXTIME(article.addTime,'%Y-%m-%d') as addTime," +
              'article.view_count as view_count,' +
              'article.article_content as article_content,' +
              'type.id as typeId,' +
              'type.typeName as typeName ' +
              'FROM article LEFT JOIN type ON article.type_id = type.Id '+
              'WHERE article.id='+id

    const result = await this.app.mysql.query(sql)
    this.ctx.body = {data: result}
  }
}

module.exports = MainController